import {
  FullscreenOutlined,
  FullscreenExitOutlined,
  RedoOutlined,
  LoadingOutlined,
  LockOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from '@ant-design/icons';
import type { Settings as LayoutSettings, ProLayoutProps } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history, useLocation } from '@umijs/max';
import React, { useState, useEffect, useCallback } from 'react';
import { AvatarDropdown, AvatarName, Footer, Question, SelectLang } from '@/components';
import { currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import '@ant-design/v5-patch-for-react-19';
import routes from '../config/routes';
import { Breadcrumb, Button } from 'antd';

// 环境常量
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const lockPath = '/lock';
const noBreadcrumbPaths = [loginPath, '/user/register', '/user/register-result', lockPath];
const originalTitle = '礼盒商城后台管理系统';

// 全局全屏状态管理
let globalFullscreenListeners: ((isFullscreen: boolean) => void)[] = [];

/**
 * 添加全局全屏状态监听器
 */
const addGlobalFullscreenListener = (listener: (isFullscreen: boolean) => void) => {
  globalFullscreenListeners.push(listener);
};

/**
 * 移除全局全屏状态监听器
 */
const removeGlobalFullscreenListener = (listener: (isFullscreen: boolean) => void) => {
  globalFullscreenListeners = globalFullscreenListeners.filter(l => l !== listener);
};

/**
 * 更新全局全屏状态
 */
const updateGlobalFullscreenState = (isFullscreen: boolean) => {
  globalFullscreenListeners.forEach(listener => listener(isFullscreen));
};

/**
 * 检查当前全屏状态
 */
const checkCurrentFullscreenState = (): boolean => {
  return !!(document as any).fullscreenElement ||
    !!(document as any).webkitFullscreenElement ||
    !!(document as any).mozFullScreenElement ||
    !!(document as any).msFullscreenElement;
};

/**
 * 全局全屏事件监听
 */
const setupGlobalFullscreenListener = () => {
  const fullscreenChangeHandler = () => {
    updateGlobalFullscreenState(checkCurrentFullscreenState());
  };

  document.addEventListener('fullscreenchange', fullscreenChangeHandler);
  document.addEventListener('webkitfullscreenchange', fullscreenChangeHandler);
  document.addEventListener('mozfullscreenchange', fullscreenChangeHandler);
  document.addEventListener('MSFullscreenChange', fullscreenChangeHandler);

  // 初始化全屏状态
  updateGlobalFullscreenState(checkCurrentFullscreenState());
};

// 设置全局全屏监听（只执行一次）
if (typeof document !== 'undefined') {
  setupGlobalFullscreenListener();
}

/**
 * 登录状态检查
 */
const checkLoginStatus = (): boolean => {
  const voucher = sessionStorage.getItem('voucher');
  const userInfo = sessionStorage.getItem('userinfo');
  const isLoggedIn = voucher === 'Login-credentials' && !!userInfo;
  if (!isLoggedIn) {
    sessionStorage.clear();
  }
  return isLoggedIn;
};

/**
 * 检查是否处于锁屏状态
 */
const checkLockStatus = (): boolean => {
  if (sessionStorage.getItem('isUnlocking') === 'true') {
    return false;
  }
  const isLocked = localStorage.getItem('isLocked') === 'true';
  const isLoggedIn = checkLoginStatus();
  return isLoggedIn && isLocked;
};

/**
 * 全屏控制 Hook
 */
const useFullscreen = () => {
  const [isFullscreen, setIsFullscreen] = useState(checkCurrentFullscreenState);

  useEffect(() => {
    const handleFullscreenChange = (newState: boolean) => {
      setIsFullscreen(newState);
    };

    // 注册全局监听器
    addGlobalFullscreenListener(handleFullscreenChange);
    
    // 初始化状态
    setIsFullscreen(checkCurrentFullscreenState());

    return () => {
      removeGlobalFullscreenListener(handleFullscreenChange);
    };
  }, []);

  const toggleFullscreen = useCallback(() => {
    if (isFullscreen) {
      if ((document as any).exitFullscreen) (document as any).exitFullscreen();
      else if ((document as any).webkitExitFullscreen) (document as any).webkitExitFullscreen();
      else if ((document as any).mozCancelFullScreen) (document as any).mozCancelFullScreen();
      else if ((document as any).msExitFullscreen) (document as any).msExitFullscreen();
    } else {
      const docEl = document.documentElement;
      if ((docEl as any).requestFullscreen) (docEl as any).requestFullscreen();
      else if ((docEl as any).webkitRequestFullscreen) (docEl as any).webkitRequestFullscreen();
      else if ((docEl as any).mozRequestFullScreen) (docEl as any).mozRequestFullScreen();
      else if ((docEl as any).msRequestFullscreen) (docEl as any).msRequestFullscreen();
    }
  }, [isFullscreen]);

  return { isFullscreen, toggleFullscreen };
};

/**
 * 递归遍历路由树，精准匹配当前路径
 */
const findMatchedRoute = (routes: any[], currentPath: string): any => {
  for (const route of routes) {
    if (route.path === currentPath) {
      return route;
    }
    if (route.routes && route.routes.length > 0) {
      const parentPath = route.path === '/' ? '' : route.path;
      for (const childRoute of route.routes) {
        const fullChildPath = `${parentPath}/${childRoute.path}`.replace(/\/+/g, '/');
        if (fullChildPath === currentPath) {
          return childRoute;
        }
      }
      const deepMatched = findMatchedRoute(route.routes, currentPath);
      if (deepMatched) {
        return deepMatched;
      }
    }
  }
  return null;
};

/**
 * 获取应用初始状态
 */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  lockScreenPassword?: string;
  isLoggedIn?: boolean;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser({ skipErrorHandler: true });
      return msg.data;
    } catch (_error) {
      if (history.location.pathname !== loginPath) {
        sessionStorage.clear();
        history.push(loginPath);
      }
    }
    return undefined;
  };

  const { location } = history;
  const currentPath = location.pathname;

  // 如果是登录页或锁屏页，不进行重定向检查
  if (currentPath === loginPath || currentPath === lockPath) {
    if (currentPath === loginPath) {
      return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
        isLoggedIn: false,
      };
    }
    return {
      fetchUserInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
      isLoggedIn: checkLoginStatus(),
    };
  }

  // 检查登录状态（非登录页且未登录）
  if (!checkLoginStatus()) {
    sessionStorage.clear();
    history.replace(loginPath);
    return {
      fetchUserInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
      isLoggedIn: false,
    };
  }

  // 检查锁屏状态（已登录但被锁定）
  if (checkLockStatus()) {
    if (localStorage.getItem('attemptedPath') !== currentPath) {
      localStorage.setItem('attemptedPath', currentPath);
    }
    history.replace(lockPath);
    return {
      fetchUserInfo,
      settings: defaultSettings as Partial<LayoutSettings>,
      isLoggedIn: true,
    };
  }

  // 正常页面，获取用户信息
  if (!noBreadcrumbPaths.includes(currentPath)) {
    const currentUser = await fetchUserInfo();
    const lockScreenPassword = undefined;

    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
      lockScreenPassword,
      isLoggedIn: true,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
    isLoggedIn: true,
  };
}

/**
 * 布局配置
 */
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const { isFullscreen, toggleFullscreen } = useFullscreen();
  const [routeKey, setRouteKey] = useState(Date.now());
  const [isRefreshing, setIsRefreshing] = useState(false);
  const location = useLocation();
  const [lastCheckedPath, setLastCheckedPath] = useState('');
  const [isChecking, setIsChecking] = useState(false);

  // 从 localStorage 初始化折叠状态
  const [collapsed, setCollapsed] = useState(() => {
    const saved = localStorage.getItem('menuCollapsed');
    return saved ? JSON.parse(saved) : false;
  });

  /**
   * 锁屏函数（仅在用户主动点击时触发，设置 isLocked 状态）
   */
  const handleLockScreen = useCallback(() => {
    // 锁屏前保存当前全屏状态
    if (isFullscreen) {
      localStorage.setItem('wasFullscreenBeforeLock', 'true');
    }
    localStorage.setItem('isLocked', 'true');
    localStorage.setItem('attemptedPath', location.pathname);
    history.push(lockPath);
  }, [location.pathname, isFullscreen]);

  /**
   * 获取当前路由名称
   */
  const getCurrentRouteName = useCallback(() => {
    const currentPath = location.pathname;
    const matchedRoute = findMatchedRoute(routes, currentPath);
    if (matchedRoute && matchedRoute.name) {
      return matchedRoute.name;
    }
    const parentPath = currentPath.split('/').slice(0, -1).join('/') || '/';
    const parentRoute = findMatchedRoute(routes, parentPath);
    if (parentRoute && parentRoute.name) {
      return parentRoute.name;
    }
    return '未知页面';
  }, [location.pathname]);

  const currentRouteName = getCurrentRouteName();

  /**
   * 刷新当前页面
   */
  const refreshPage = useCallback(() => {
    setIsRefreshing(true);
    setRouteKey(Date.now());
    setTimeout(() => setIsRefreshing(false), 300);
  }, []);

  /**
   * 生成面包屑数据
   */
  const getBreadcrumbItems = useCallback(() => {
    const currentPath = location.pathname;
    const items: any[] = [];
    if (noBreadcrumbPaths.includes(currentPath)) {
      return items;
    }
    const pathSegments = currentPath.split('/').filter(Boolean);
    let currentFullPath = '';
    pathSegments.forEach((segment) => {
      currentFullPath += `/${segment}`;
      const matchedRoute = findMatchedRoute(routes, currentFullPath);
      if (matchedRoute?.name) {
        items.push({
          title: matchedRoute.name,
          key: currentFullPath,
        });
      }
    });
    return items;
  }, [location.pathname]);

  /**
   * 切换菜单折叠状态（同步更新 title）
   */
  const toggleCollapsed = useCallback(() => {
    const newCollapsed = !collapsed;
    setCollapsed(newCollapsed);
    localStorage.setItem('menuCollapsed', JSON.stringify(newCollapsed));

    setInitialState((preInitialState) => ({
      ...preInitialState,
      settings: {
        ...preInitialState?.settings,
        collapsed: newCollapsed,
        title: newCollapsed ? '' : originalTitle,
      },
    }));
  }, [collapsed, setInitialState]);

  /**
   * 初始化时同步折叠状态与 title
   */
  useEffect(() => {
    setInitialState((preInitialState) => ({
      ...preInitialState,
      settings: {
        ...preInitialState?.settings,
        collapsed: collapsed,
        title: collapsed ? '' : originalTitle,
      },
    }));
  }, [collapsed, setInitialState]);

  /**
   * 安全的路由检查函数
   */
  const checkAuthSafely = useCallback(() => {
    if (isChecking) return;

    const currentPath = location.pathname;

    if (currentPath === lastCheckedPath) {
      return;
    }

    setLastCheckedPath(currentPath);
    setIsChecking(true);

    // 如果是登录页或锁屏页，不进行重定向
    if (currentPath === loginPath || currentPath === lockPath) {
      setIsChecking(false);
      return;
    }

    // 检查登录状态
    if (!checkLoginStatus()) {
      sessionStorage.clear();
      setTimeout(() => {
        history.replace(loginPath);
        setIsChecking(false);
      }, 150);
      return;
    }

    // 检查锁屏状态
    if (checkLockStatus()) {
      if (localStorage.getItem('attemptedPath') !== currentPath) {
        localStorage.setItem('attemptedPath', currentPath);
      }
      setTimeout(() => {
        history.replace(lockPath);
        setIsChecking(false);
      }, 150);
      return;
    }

    setIsChecking(false);
  }, [location.pathname, lastCheckedPath, isChecking]);

  // 使用 useEffect 统一管理路由检查
  useEffect(() => {
    checkAuthSafely();
  }, [checkAuthSafely]);

  // 简化 onPageChange，避免重复检查
  const handlePageChange = useCallback(() => {
    const { location: historyLocation } = history;
    const currentPath = historyLocation.pathname;

    if (currentPath === loginPath || currentPath === lockPath) {
      return;
    }

    if (!checkLoginStatus()) {
      sessionStorage.clear();
      history.replace(loginPath);
      return;
    }

    if (checkLockStatus()) {
      localStorage.setItem('attemptedPath', currentPath);
      history.replace(lockPath);
    }
  }, []);

  return {
    collapsed: collapsed,   // 折叠状态

    // 顶部中间区域：折叠按钮 + 面包屑
    headerContentRender: () => (
      <div className="header-content">
        <Button
          type="text"
          icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          onClick={toggleCollapsed}
          title={collapsed ? '展开菜单' : '折叠菜单'}
        />
        <Breadcrumb
          items={getBreadcrumbItems()}
          separator=">"
          style={{ fontSize: '14px' }}
        />
      </div>
    ),

    // 顶部右侧操作区
    actionsRender: () => [
      checkLoginStatus() && location.pathname !== lockPath && (
        <LockOutlined
          key="lock"
          onClick={handleLockScreen}
          title="锁定屏幕"
          onMouseEnter={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.06)';
            (e.target as HTMLElement).style.borderRadius = '4px';
          }}
          onMouseLeave={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'transparent';
          }}
        />
      ),
      isFullscreen ? (
        <FullscreenExitOutlined
          key="exit-fullscreen"
          onClick={toggleFullscreen}
          title="退出全屏"
          onMouseEnter={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.06)';
            (e.target as HTMLElement).style.borderRadius = '4px';
          }}
          onMouseLeave={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'transparent';
          }}
        />
      ) : (
        <FullscreenOutlined
          key="fullscreen"
          onClick={toggleFullscreen}
          title="全屏显示"
          onMouseEnter={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.06)';
            (e.target as HTMLElement).style.borderRadius = '4px';
          }}
          onMouseLeave={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'transparent';
          }}
        />
      ),
      isRefreshing ? (
        <LoadingOutlined
          key="refresh-loading"
          spin
          title="刷新中..."
          onClick={refreshPage}
          onMouseEnter={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.06)';
            (e.target as HTMLElement).style.borderRadius = '50%';
          }}
          onMouseLeave={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'transparent';
          }}
        />
      ) : (
        <RedoOutlined
          key="refresh"
          title="刷新页面"
          onClick={refreshPage}
          onMouseEnter={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.06)';
            (e.target as HTMLElement).style.borderRadius = '50%';
          }}
          onMouseLeave={(e) => {
            (e.target as HTMLElement).style.backgroundColor = 'transparent';
          }}
        />
      ),
      <SelectLang key="lang" />,
    ],

    // 用户头像下拉菜单配置
    avatarProps: initialState?.currentUser ? {
      src: initialState.currentUser.avatar || 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
      title: <AvatarName />,
      render: (_, avatarChildren) => <AvatarDropdown>{avatarChildren}</AvatarDropdown>,
    } : undefined,

    // 页脚
    footerRender: () => <Footer />,

    // 页面切换时的回调
    onPageChange: handlePageChange,

    // 隐藏菜单头部
    menuHeaderRender: undefined,

    // 子组件渲染
    childrenRender: (children) => (
      <div key={routeKey}>
        {children}
      </div>
    ),

    // 动态 title 配置
    title: initialState?.settings?.title || originalTitle,

    // 继承初始状态中的布局配置
    ...initialState?.settings,

    // 布局配置
    layout: 'mix',   // 混合布局
    fixedHeader: true,   // 固定头部
    fixSiderbar: true,   // 固定侧边栏
  };
};

/**
 * 请求配置
 */
export const request: RequestConfig = {
  ...errorConfig,
};